package com.example.serverSide.commom.handler;


import com.example.serverSide.commom.exception.NotLoginException;
import com.example.serverSide.commom.util.BaseContext;
import com.example.serverSide.commom.util.TokenUtil;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        if (HttpMethod.OPTIONS.toString().equals(method)) {
            return true;
        }
        String token = request.getHeader("Authorization");
        System.out.println("token: "+token);

        if (!StringUtils.hasLength(token)){
            throw new NotLoginException("Invalid User", 401);
        }
        if (!TokenUtil.checkToken(token)){
            throw new NotLoginException("Invalid User", 401);
        }
        Long userId = (Long) TokenUtil.getInfo(token, "id");
        BaseContext.setCurrentId(userId);
        return true;
    }
}
